package com.dnake.misc;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class SysForward {
	public static class Data {
		public long id;
		public String ids;
	}

	private static int MAX = 1000;
	private static Data data[] = new Data[MAX];
	private static int max = 0;

	private static String url = "/dnake/cfg/sys_forward.txt";

	public static String get(long id) {
		for(int i=0; i<max; i++) {
			if (data[i] != null && data[i].id == id)
				return data[i].ids;
		}
		return null;
	}

	public static void set(long id, String ids) {
		for(int i=0; i<max; i++) {
			if (data[i] != null && data[i].id == id) {
				if (ids == null) {
					max--;
					data[i] = data[max];
				} else
					data[i].ids = ids;
				save();
				return;
			}
		}
		if (ids != null && max < MAX) {
			data[max] = new Data();
			data[max].id = id;
			data[max].ids = ids;
			max++;
			save();
		}
	}

	private static void loadData(String ss) {
		if (max >= MAX)
			return;

		StringTokenizer tk = new StringTokenizer(ss, "->");
		String id = tk.nextToken();
		String ids = tk.nextToken();

		if (id == null || id.length() == 0 || ids == null || ids.length() == 0)
			return;

		data[max] = new Data();
		data[max].id = Integer.parseInt(id);
		data[max].ids = ids;
		max++;
	}

	public static void load() {
		max = 0;
		for(int i=0; i<MAX; i++)
			data[i] = null;

		try {
			String s;
			FileInputStream in = new FileInputStream(url);
			BufferedReader r = new BufferedReader(new InputStreamReader(in));
			while ((s = r.readLine()) != null) {
				if (s.length() >= 4)
					loadData(s);
			}
			r.close();
			in.close();
		} catch (IOException e) {
			//e.printStackTrace();
		}
	}

	public static void save() {
		try {
			FileOutputStream out = new FileOutputStream(url);
			for(int i=0; i<max; i++) {
				Data d = data[i];
				if (d != null && d.ids != null) {
					String s = String.valueOf(d.id)+"->"+d.ids+"\n";
					out.write(s.getBytes());
				}
			}
			out.flush();
			out.getFD().sync();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void reset() {
		max = 0;
		for(int i=0; i<MAX; i++)
			data[i] = null;
	}
}
